#include "infosave.h"
#include "ui_infosave.h"
#include "exportexcelobject.h"
#include "mainwindow.h"
infoSave::infoSave(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::infoSave)
{
    ui->setupUi(this);
    qTable();
    setTableSty();
}

infoSave::~infoSave()
{
    delete ui;
}

//保存数据为excel
void infoSave::on_btn_Save_clicked()
{
//    获取弹出框输入文件名
    QString fileName = QFileDialog::getSaveFileName(this, tr("Excel file"), qApp->applicationDirPath (),
                                                    tr("Excel Files (*.xls)"));
    if (fileName.isEmpty())
        return;
//                            文件名,创建后的名字,数据源
    ExportExcelObject obj(fileName, "infoData", ui->InfoView);
//    obj.addField(3, "colum4", "char(20)");
//    obj.addField(1, "colum2", "char(20)");
//    obj.addField(2, "colum3", "char(20)");

//    obj.addField(0, "课程编号", "char(20)");
    obj.addField(1, "课程名称", "char(20)");
    obj.addField(2, "任课老师", "char(20)");

    obj.addField(3, "学分", "char(20)");
    obj.addField(4, "课程性质", "char(20)");
    obj.addField(5, "开课院系", "char(20)");

//    设置进度条
    ui->progressBar->setValue(0);
    ui->progressBar->setMaximum(ui->InfoView->model()->rowCount());

//    监听进度条变化
    connect(&obj, SIGNAL(exportedRowCount(int)), ui->progressBar, SLOT(setValue(int)));
//    获取写入数据条数
    int retVal = obj.export2Excel();
    if( retVal > 0)
    {
        QMessageBox::information(this, tr("Done"),
                                 QString(tr("%1 records exported!")).arg(retVal)
                                 );
    }
}

//更新数据表
void infoSave::qTable()
{
    QString str = QString("SELECT * FROM %1").arg(tableName);
    model.setQuery(str);
    ui->InfoView->setModel(&model);
}

void infoSave::setTableSty()
{
//    进度条默认0
    ui->progressBar->setValue(0);
//    让sql数据填满容器
    ui->InfoView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
//    ui->InfoView->verticalHeader()->hide();//    隐藏第一列
    ui->InfoView->setAlternatingRowColors(true);//使表格颜色交错功能为真
    ui->InfoView->horizontalHeader()->setStyleSheet("QHeaderView::section{background:rgb(23, 142, 150);color: #fde3c8;}");//设置表头背景和字体颜色
}
